package com.ddxz.hospital.util;

import com.alibaba.fastjson.JSON;
import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

/**
 * class description
 *
 * @author 朱宗刚
 * @version 1.0.0
 * @date 2020/9/23
 */

public class JsonHandler extends BaseTypeHandler<JSON> {
    @Override
    public void setNonNullParameter(PreparedStatement preparedStatement, int i, JSON json, JdbcType jdbcType) throws SQLException {
        preparedStatement.setString(i, json.toJSONString());
    }

    @Override
    public JSON getNullableResult(ResultSet resultSet, String s) throws SQLException {
        return this.getJSON(resultSet.getString(s));
    }

    private JSON getJSON(String string) {
        if (null == string) {
            return null;
        } else {
            return (JSON)('[' == string.charAt(0) ? JSON.parseArray(string) : JSON.parseObject(string));
        }
    }

    @Override
    public JSON getNullableResult(ResultSet resultSet, int i) throws SQLException {
        return this.getJSON(resultSet.getString(i));
    }

    @Override
    public JSON getNullableResult(CallableStatement callableStatement, int i) throws SQLException {
        return this.getJSON(callableStatement.getString(i));
    }
}
